package cn.dslcode.security.config.security;

import cn.dslcode.security.config.security.rememberme.RememberMeAuthenticationConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter;

@Configuration
@EnableWebSecurity
//用于@PreAuthorize的生效,基于方法的权限控制，允许进入页面方法前检验，
// prePostEnabled :决定Spring Security的前注解是否可用 [@PreAuthorize,@PostAuthorize,..]
//secureEnabled : 决定是否Spring Security的保障注解 [@Secured] 是否可用
//jsr250Enabled ：决定 JSR-250 annotations 注解[@RolesAllowed..] 是否可用.
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
//覆盖默认的spring security提供的配置
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomSecurityConstant securityConstant;

    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;
    @Autowired
    private CustomAuthenticationHandlers authenticationHandlers;
    @Autowired
    private RememberMeAuthenticationConfig rememberMeConfig;


    /**
     * 忽略静态文件
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(securityConstant.getUri().getStaticResource());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests().antMatchers(securityConstant.getUri().getPermitAll()).permitAll()
            .anyRequest().authenticated()
            .and()
            // 在 默认的 RememberMeAuthenticationFilter 前添加
            .addFilterBefore(
                rememberMeConfig.getFilterAndSet(super.authenticationManager(), authenticationHandlers.getAuthenticationSuccessHandler()),
                RememberMeAuthenticationFilter.class
            )
            // 在 默认的 UsernamePasswordAuthenticationFilter 前添加
            .addFilterBefore(
                new CustomCaptchaVerifyFilter(
                    super.authenticationManager(),
                    rememberMeConfig.getRememberMeServices(),
                    authenticationHandlers.getAuthenticationSuccessHandler(),
                    authenticationHandlers.getAuthenticationFailureHandler(),
                    securityConstant.getUri().getLoginForm(),
                    securityConstant.getParameterName().getCaptchaCode()
                ),
                UsernamePasswordAuthenticationFilter.class
            )
            .formLogin()
            .loginPage(securityConstant.getUri().getLoginForm())
            .permitAll()
            .and()
            .logout()
            .logoutUrl(securityConstant.getUri().getLogout())
            .permitAll()
            .clearAuthentication(true)
            .deleteCookies(securityConstant.getRememberMe().getCookieName())
            .invalidateHttpSession(true)
            .logoutSuccessHandler(authenticationHandlers.getLogoutSuccessHandler())
            .and()
            .exceptionHandling()
            .authenticationEntryPoint(authenticationHandlers.getAuthenticationEntryPoint())
            .accessDeniedHandler(authenticationHandlers.getAccessDenyHandler())
            .and()
            .httpBasic().disable()
            .headers().frameOptions().disable()
            .and()
            .csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .authenticationProvider(rememberMeConfig.getAuthenticationProvider())
            .authenticationProvider(customAuthenticationProvider);
    }

}